<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>webSocket</title>
</head>
<body>
    <h1>Chat Room</h1>
    <input id="sendTxt" type="text"/>
    <button id="sendBtn">发送</button>
    <div id="recv"></div>
    <script>
        var webSocket =new WebSocket("ws://localhost:3000/");
        function showMassage(type,data){
            var div =document.createElement('div')
            div.innerHTML=data;
            if(type=='enter'){
                div.style.color="blue"
            }else if(type=='leave'){
                div.style.color="red"
            }else if(type=="message"){
                div.style.color="black"
            }
            document.body.appendChild(div);
        }

        webSocket.onopen=function(){
            console.log("websocket open");
            document.getElementById("sendBtn").onclick=function(){
                var txt=document.getElementById("sendTxt").value;
                if(txt){
                    webSocket.send(txt);
                }
            }
        }
        webSocket.onclose =function(){
            console.log('websocket close');
        }
        webSocket.onmessage=function(e){
            console.log(e.data);
            var mes=JSON.parse(e.data);
            showMassage(mes.type,mes.data);
        }
    </script>
</body>
</html>